import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_todo/common/app.request.dart';
import 'package:flutter_todo/models/request_error/request_error.model.dart';
import 'package:flutter_todo/routes/login/login.route.dart';
import 'package:flutter_todo/routes/todo/todo.route.dart';

class LoginFormWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    TextEditingController _account = TextEditingController(text: 'alan');
    TextEditingController _password = TextEditingController(text: 'alan');

    return Column(
      children: <Widget>[
        TextField(
          controller: _account,
          decoration: InputDecoration(
            labelText: '账号',
            hintText: '请输入账号',
            prefixIcon: Icon(Icons.person),
          ),
        ),
        TextField(
          controller: _password,
          decoration: InputDecoration(
            labelText: '密码',
            hintText: '请输入密码',
            prefixIcon: Icon(Icons.lock),
          ),
          obscureText: true,
        ),
        FlatButton(
          color: Colors.blue,
          highlightColor: Colors.blue[700],
          colorBrightness: Brightness.dark,
          splashColor: Colors.grey,
          child: Text('登录'),
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
          onPressed: () async {
            try {
              await AppRequest().login(_account.text, _password.text);
              // Navigator.pushNamed(context, TodoRoute.routeName);
              Navigator.pushNamedAndRemoveUntil(context, TodoRoute.routeName,
                  ModalRoute.withName(LoginRoute.routeName));
            } on DioError catch (e) {
              RequestError requestError =
                  RequestError.fromJson(e.response.data);
              Scaffold.of(context)
                ..removeCurrentSnackBar()
                ..showSnackBar(SnackBar(
                  content: Text('${requestError.error}'),
                ));
            }
          },
        ),
      ],
    );
  }
}
